package com.a01_2021.thousandstimes.general.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.entity.School;
import com.a01_2021.thousandstimes.general.mapper.SchoolMapper;
import com.a01_2021.thousandstimes.general.service.ISchoolService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-04-03
 */
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements ISchoolService {

    @Resource
    SchoolMapper schoolMapper;

    /**
     * 用于添加在校表现
     *
     * @param school 在校表现实体
     * @return 在校表现实体类
     * @throws CustomException 当存在同名、同生日的人时抛出该异常
     */
    @Override
    public School add(School school) throws CustomException {
        //判定是否已经存在该人
        QueryWrapper<School> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", school.getName());
        queryWrapper.eq("birthday", school.getBirthday());
        if (schoolMapper.selectCount(queryWrapper) > 0) {
            throw new CustomException("该学习成绩已存在", 400);
        }
        schoolMapper.insert(school);
        return school;
    }

    /**
     * 通过名字与生日获取在校表现
     *
     * @param name     用户姓名
     * @param birthday 生日
     * @return 在校表现列表
     */
    @DS("master")
    public List<School> get(String name, LocalDate birthday) {
        QueryWrapper<School> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        queryWrapper.eq("birthday", birthday);
        return schoolMapper.selectList(queryWrapper);
    }

    /**
     * 计算当前学习成绩均分
     *
     * @param name     用户姓名
     * @param birthday 生日
     * @return double
     */
    public double getAvgScore(String name, LocalDate birthday) {
        double sum = 0.0;
        List<School> schoolList = this.get(name, birthday);
        for (School item : schoolList) {
            sum += item.getScore();
        }
        return sum / schoolList.size();
    }
}
